<!-- 里程碑管理 弹窗 -->
<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="showMilestoneDialog"
      :before-close="cancel"
      width="1254px"
      append-to-body
      custom-class="dialog-box"
    >
      <el-row :gutter="10" class="mb20">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click="handleAdd"
            >添加里程碑节点</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="milestoneList" border :cell-style="columnStyle">
        <el-table-column
           label="里程碑名称"
          align="center"
          prop="milestoneName"
          width="203"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span v-show="!scope.row.show">{{ scope.row.milestoneName }}</span>
            <el-input
              v-show="scope.row.show"
              v-model="scope.row.milestoneName"
              placeholder="请输入"
              maxlength="30"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="计划完成时间" align="center" width="203">
          <template slot-scope="scope">
            <span v-show="!scope.row.show">{{
              getDay(scope.row.plannedCompletionTime)
            }}</span>
            <el-date-picker
              v-model="scope.row.plannedCompletionTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              size="medium"
              :clearable="false"
              v-show="scope.row.show"
              style="width: 100%"
            >
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="实际完成时间" align="center" width="203">
          <template slot-scope="scope">
            <span v-show="!scope.row.show">{{
              getDay(scope.row.actualCompletionTime)
            }}</span>
            <el-date-picker
              v-model="scope.row.actualCompletionTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              size="medium"
              v-show="scope.row.show"
              style="width: 100%"
            >
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column
           label="完成标准"
          align="center"
          prop="completionCriteria"
          width="203"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span v-show="!scope.row.show">{{ scope.row.completionCriteria }}</span>
            <el-input
              v-show="scope.row.show"
              v-model="scope.row.completionCriteria"
              placeholder="请输入"
              maxlength="100"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="附件"
          align="center"
          prop="enclosure.fileName"
          width="203"
        >
          <template slot-scope="scope">
            <span v-show="!scope.row.show">
              <img
              src="@/assets/images/tripartite/icon_files.png"
              class="files-icon"
              v-show="scope.row.enclosure.fileName"
            />{{ scope.row.enclosure.fileName }}</span>
            <el-upload
              v-show="scope.row.show"
              :ref="`uploadRow${scope.$index}`"
              class="upload-demo"
              :action="upload.url"
              accept=".png, .jpg, .pdf, .xls, .doc, .docx, .zip, .rar, .7z"
              :headers="upload.headers"
              :limit="1"
              :on-progress="handleFileUploadProgress"
              :on-success="(response,file)=>{return handleFileSuccess(response ,file ,scope.row,scope.$index)}"
              
            >
              <el-input
                v-model="scope.row.enclosure.fileName"
                placeholder="请选择文件"
                clearable
              />
            </el-upload>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="medium"
              type="text"
              v-show="!scope.row.show"
              :disabled="scope.row.milestoneName==='项目建议书审批通过'||scope.row.milestoneName==='可研报告审批通过'||scope.row.milestoneName==='初设评审报告'||scope.row.milestoneName==='合同签订'"
              @click="handleDataScope(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="text"
              v-show="scope.row.show"
              @click="handleSure(scope.row)"
              >确定</el-button
            >
            <el-button
              size="medium"
              type="text"
              v-show="!scope.row.show"
              :disabled="scope.row.milestoneName==='项目建议书审批通过'||scope.row.milestoneName==='可研报告审批通过'||scope.row.milestoneName==='初设评审报告'||scope.row.milestoneName==='合同签订'"
              @click.native.prevent="
                deleteRow(scope.$index, milestoneList)
              "
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { addMilestoneInfo ,updateMilestoneInfo ,listMilestoneInfo, getFinishTimeOfMilestone} from "@/api/projectCompany/myProject";

export default {
  name: "MilestoneDialog",
  props: {
    showMilestoneDialog: {
      type: Boolean,
      default: false,
    },
    proId:{
      type: String,
      default: ''
    },
    rowData:{
      type: Object,
      default: ()=>{}
    },
  },
  inject:['reload'],
  data() {
    return {
      // 弹出层标题
      title: "里程碑管理",
      // 弹出窗是否显示
      showEditDialog:false,
      // 查询参数
      queryParams:{proId:undefined,milestoneInformationList:[]},
      // 里程碑信息列表
      milestoneList: [
        { milestoneName: "项目建议书审批通过" ,plannedCompletionTime:"",enclosure:{fileName:'',fileUrl:''},show:false},
        { milestoneName: "可研报告审批通过" ,plannedCompletionTime:"",enclosure:{fileName:'',fileUrl:''},show:false},
        { milestoneName: "初设评审报告" ,plannedCompletionTime:"",enclosure:{fileName:'',fileUrl:''},show:false},
        { milestoneName: "合同签订" ,plannedCompletionTime:"",enclosure:{fileName:'',fileUrl:''},show:false},
        { milestoneName: "上线试运行" ,plannedCompletionTime:"",enclosure:{fileName:'',fileUrl:''},show:false},
        { milestoneName: "合规审查" ,plannedCompletionTime:"",enclosure:{fileName:'',fileUrl:''},show:false},
        { milestoneName: "初验" ,plannedCompletionTime:"",enclosure:{fileName:'',fileUrl:''},show:false},
        { milestoneName: "终验" ,plannedCompletionTime:"",enclosure:{fileName:'',fileUrl:''},show:false},
      ],
      // 上传文件参数 当前行
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/file/upload",
        // 上传文件名称
        fileName: "请选择文件",
      },
      // 查询参数对应id
      relationId:undefined,
      // 控制按钮操作
    };
  },
  watch:{
      showMilestoneDialog(val){
        console.log('监听里程碑',val);
          this.relationId = this.rowData.relationId
          if(val==true && this.relationId && this.relationId !=null){
              this.getView()
          } else {
            this.setTopTwoMilestone()
          }
      },
  },
  methods: {
    // 获取列表
    getView(){
      this.relationId = this.rowData.relationId
      if(this.relationId && this.relationId !=null){
        listMilestoneInfo(this.relationId).then(res=>{
            if(res.code == 200){
                this.milestoneList=res.rows
                this.milestoneList.map((item) => {
                  this.$set(item, "show", false);
                  if(item.enclosureFile&&item.enclosureFile!=null){
                    item.enclosure=item.enclosureFile
                  }else{
                    item.enclosure={fileName:'',fileUrl:''}
                  }
                });


            }
        })
      }      
    },
    /** 对表格单列样式更改 */
    columnStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex == 0) {
        //第1列的背景色就改变
        return "background:#f8f8f9";
      }
    },
    /** 取消按钮 */
    cancel() {
      this.$emit("changeShowDialog", "false"); //调用父组件的自定义事件，并传值
    },
    /** 确定按钮 */
    submitForm() {
      this.relationId = this.rowData.relationId
      this.queryParams.proId=this.proId
      let pass = this.milestoneList.every(item => !(item.show == true))
      if (!pass) return this.$message.error("请先确定正在编辑的内容后保存")
      // this.queryParams.milestoneInformationList = this.milestoneList
      this.queryParams.milestoneInformationList = this.milestoneList.filter(
        (item) => item.show == false
      );
      if (this.queryParams.milestoneInformationList.length == 0) {
        return this.$message.error("请先确定填写内容后保存");
      }
      // for(let i = 0; i < this.queryParams.milestoneInformationList.length; i++) {
      //   if( this.queryParams.milestoneInformationList[i].plannedCompletionTime == "") {
      //     return this.$message.error("请先编辑选择计划完成时间后保存");
      //   }
      // }
      if (this.relationId == undefined || this.relationId == "" || this.relationId == null) {
        addMilestoneInfo(this.queryParams).then((response) => {
          this.msgSuccess("提交成功");
          this.$emit("changeShowDialog", "false");
          this.reload();
        });
      } else {
        updateMilestoneInfo(this.queryParams).then((response) => {
          this.msgSuccess("修改成功");
          this.$emit("changeShowDialog", "false");
          this.reload();
        });
      }
    },
    /** 新增按钮操作 */
    handleAdd(){
      this.$nextTick(()=>{
        this.milestoneList.push({
                milestoneName: "",
                plannedCompletionTime: "",
                actualCompletionTime: "",
                completionCriteria: "",
                enclosure:{fileName:'',fileUrl:''},
                show: true,
              });
      })
      this.$forceUpdate(); //强制刷新，解决页面不会重新渲染的问题
    },
    /** 编辑按钮操作 */
    handleDataScope(row) {
      row.show = true
    },
    // 确定按钮操作
    handleSure(row) {
      row.show = false;
    },
    /** 删除按钮操作 */
    deleteRow(index, rows) {
      this.$confirm("是否确认删除 ？", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "del_box",
      })
        .then(function () {
           rows.splice(index, 1);
        })
        .then(() => {
          // this.getList();
          this.msgSuccess("删除成功");
        });      
    },
 
    // 文件上传中处理 （当前行）
    handleFileUploadProgress(event, file, fileList) {
      console.log("文件上传中", file);
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, row,index) {
      console.log("文件上传成功", response, file ,row,index);
      // console.log('ref',this.$refs[`uploadRow${index}`]);
      this.$refs[`uploadRow${index}`].clearFiles();
      if(response.code!=500&&response.data){
        this.upload.fileName = file.name;
        row.enclosure.fileName = file.name
        row.enclosure.fileUrl = response.data.fileUrl;
        this.$forceUpdate(); //强制刷新，解决页面不会重新渲染的问题
      }else{
        this.$message.error(response.msg)
      }
    },
    // 查询默认的头两个节点时间
    setTopTwoMilestone() {
      getFinishTimeOfMilestone(this.proId).then(res => {
            let tmp1 = {... this.milestoneList[1]}
            let tmp0 = {... this.milestoneList[0]}
            let tmp2 = {... this.milestoneList[2]}
            let tmp3 = {... this.milestoneList[3]}
            tmp1.actualCompletionTime = res.programApprovalTime // 方案审批通过时间
            tmp0.actualCompletionTime = res.applicationApprovalTime // 项目申报通过时间
            tmp2.actualCompletionTime = res.preliminaryDesignSchemeApprovalTime // 初设方案审核通过时间
            tmp3.actualCompletionTime = res.signingTime // 合同备案的签约时间
            this.milestoneList.splice(0,4, tmp0, tmp1, tmp2, tmp3)
      }).catch(err => {
        console.log(err)
      })
    },
    // 截取日期
    getDay(timeStr) {
      if (timeStr) {
        return timeStr.substr(0,10)
      }
      return timeStr
    }
  },
};
</script>

<style lang="scss" scoped>
// 文件上传
.files_upload_box {
  width: 373px;
  height: 36px;
  line-height: 36px;
  font-size: 13px;
  font-family: PingFang SC, PingFang SC-Regular;
  color: #afb3bd;
  border: 1px solid #d8d8d8;
  border-radius: 4px;
  padding-left: 15px;
  position: relative;
  .img_box {
    height: 36px;
    width: 36px;
    background: #0d72ff;
    text-align: center;
    border-radius: 0px 4px 4px 0px;
    position: absolute;
    right: -1px;
    top: -1px;
    img {
      width: 16px;
      height: 16px;
    }
  }
}
</style>
<style lang="scss">
/* 弹出窗样式 */
.dialog-box {
  .el-dialog__body {
    padding: 24px 48px 24px 48px;
    border-top: 1px solid #ebecef;
    border-bottom: 1px solid #ebecef;
    label {
      font-weight: 400 !important;
    }
    .last-form-item {
      margin-bottom: 0;
    }
  }
  .el-dialog__footer {
    padding: 16px 20px;
  }
  .el-dialog__headerbtn {
    background: url("../../../../assets/images/icon_dialog_close.png");
    background-size: 100%;
    width: 16px;
    height: 16px;
    .el-dialog__close {
      visibility: hidden;
    }
  }
}
/* 删除弹出框样式 */
.del_box {
  width: 345px;
  height: 175px;
  .el-message-box__headerbtn {
    background: url("../../../../assets/images/icon_dialog_close.png");
    background-size: 100%;
    width: 16px;
    height: 16px;
    .el-message-box__close {
      visibility: hidden;
    }
  }
  .el-message-box__content {
    padding: 26px 95px;
    font-size: 16px;
    .el-message-box__status.el-icon-warning {
      color: #ea4747;
    }
    .el-message-box__status + .el-message-box__message {
      padding-right: 0;
    }
  }
}
// 文件图标样式更改
.files-icon {
  width: 16px;
  height: 16px;
  margin-right: 10px;
  position: relative;
  top: 4px;
}
</style>
